"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PayReqHandler = void 0;
const UserDao_1 = require("../src/dao/UserDao");
const SystemSettingDao_1 = require("../gm_server/dao/SystemSettingDao");
const ErrorCode_1 = require("../src/config/ErrorCode");
const GoodConfig_1 = require("../src/config/GoodConfig");
const DateUtil_1 = require("../src/engine/utils/DateUtil");
const Logger_1 = require("../src/engine/utils/Logger");
const Md5Helper_1 = require("../src/engine/utils/Md5Helper");
const WebUtil_1 = require("../src/engine/utils/WebUtil");
const ResponseModel_1 = require("../src/model/ResponseModel");
const ChargeDao_1 = require("./dao/ChargeDao");
const request = require('request');
const crypto = require("crypto");
const routerMap = {
    req_pay: "/req_pay",
    third_alipay_notify_post: "/third_alipay_notify_post"
};
const payVersion = '10';
const mer_no = '6888803037146';
const mer_key = 'tXYkMkROjsFsnhnqoBsYgsT56WPunCDTIx1yFRgA5aTniHHPKPTFfz0C9A2JisNJiogZ8YhOxR4=';
const md5key = 'hpEucHLqLdK9oObPLOyWI6ZVhFUX1s8T3PiG0hLdap0+p8X6lYV9FUxUg8ngn6dX0pPBc949NC9TC+UoR5cMtEc84dPN9EkK+DMxX6EUbBNWi6u4aEZy59T/lmqHq/F2oHY4ii79/oJixuz+UKFTiw==';
const sandPubkey = '-----BEGIN CERTIFICATE-----\r\nMIIDJjCCAg6gAwIBAgIGAViVUCVLMA0GCSqGSIb3DQEBCwUAMFQxDTALBgNVBAMT\r\nBFNBTkQxDTALBgNVBAsTBFNBTkQxDTAL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\n-----END CERTIFICATE-----\r\n';
class PayReqHandler {
    constructor() {
        this.orderOnlyId = 1;
    }
    init(app) {
        for (const key in routerMap) {
            app.use(routerMap[key], this.onBaseRoot.bind(this));
        }
    }
    onBaseRoot(req, resp) {
        try {
            let ip = WebUtil_1.WebUtil.getIpByExpressReq(req);
            Logger_1.Logger.log("onBaseRoot=req=", ip, req.baseUrl);
            if (req.baseUrl == routerMap.req_pay) {
                this.checkBody(ip, req, resp, this.on_req_pay.bind(this));
            }
            else if (req.baseUrl == routerMap.third_alipay_notify_post) {
                this.third_alipay_notify_post(req, resp, ip);
            }
        }
        catch (error) {
            Logger_1.Logger.warn("onBaseRoot error", error);
        }
    }
    checkBody(ip, req, resp, callback) {
        if (req.body) {
            try {
                let jsonObj = JSON.parse(req.body);
                let k = jsonObj["k"];
                let data = jsonObj["data"];
                if (k == Md5Helper_1.Md5Helper.getMd5_encrypt(JSON.stringify(data))) {
                    callback && callback(req, resp, data, ip);
                }
                else {
                    Logger_1.Logger.warn("收到非法Http请求 key", req.baseUrl, ip, req.body);
                    resp.end();
                }
            }
            catch (error) {
                Logger_1.Logger.warn("收到非法Http请求body", req.baseUrl, ip, req.body, error);
                resp.end();
            }
        }
        else {
            resp.end();
        }
    }
    on_req_pay(req, resp, data, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            Logger_1.Logger.log("on_req_pay===", data);
            let goodid = data["goodid"];
            let goodConfig = GoodConfig_1.GoodConfig.configMap.get(goodid);
            if (goodConfig) {
                let userid = data["userid"];
                let isExist = yield UserDao_1.UserDao.is_user_exist_by_userid(userid);
                if (isExist) {
                    let order_id = this.productOrder(userid);
                    let notify_url = `http://newpay.v81.cn/third_alipay_notify_post`;
                    let date = new Date();
                    let create_time = DateUtil_1.default.formatDateStr4(date.getTime());
                    let order_amt = goodConfig.rmb.toFixed(2);
                    let cheapUserList = [100026, 100027];
                    if (cheapUserList.includes(userid)) {
                        order_amt = "0.01";
                    }
                    let return_url = "";
                    let create_ip = ip.replace(/\./g, '_');
                    let pay_extra = '{}';
                    let accsplit_flag = 'NO';
                    let sign_type = 'MD5';
                    let store_id = '000000';
                    date.setMinutes(date.getMinutes() + 15);
                    let expire_time = DateUtil_1.default.formatDateStr4(date.getTime());
                    let goods_name = goodConfig.getGooName();
                    let product_code = '02020004';
                    let clear_cycle = '3';
                    let jump_scheme = 'sandcash://scpay';
                    let merData = [{ "s": "Android", "n": "大家乐竞技", "id": "com.game.dajialejingji", "sc": "sandcash://scpay" }, { "s": "IOS", "n": "大家乐竞技", "id": "com.game.dajialejingji", "sc": "sandcash://scpay" }];
                    let reqData = {
                        version: payVersion,
                        mer_no: mer_no,
                        mer_key: mer_key,
                        mer_order_no: order_id,
                        create_time: create_time,
                        order_amt: order_amt,
                        notify_url: notify_url,
                        return_url: return_url,
                        create_ip: create_ip,
                        pay_extra: pay_extra,
                        accsplit_flag: accsplit_flag,
                        sign_type: sign_type,
                        store_id: store_id,
                        expire_time: expire_time,
                        goods_name: goods_name,
                        product_code: product_code,
                        clear_cycle: clear_cycle,
                        jump_scheme: jump_scheme,
                        meta_option: JSON.stringify(merData)
                    };
                    // 不参与签名属性列表
                    let noSigns = ['return_url', 'expire_time', 'goods_name', 'product_code', 'clear_cycle', 'jump_scheme', 'meta_option'];
                    let paramArr = [];
                    for (let key in reqData) {
                        let val = reqData[key];
                        if (val === '' || noSigns.indexOf(key) >= 0) {
                            continue;
                        }
                        paramArr.push({ key, val });
                    }
                    paramArr.sort((a, b) => {
                        return a.key > b.key ? 1 : -1;
                    });
                    let strArr = [];
                    for (let i = 0; i < paramArr.length; i++) {
                        let item = paramArr[i];
                        strArr.push(`${item.key}=${item.val}`);
                    }
                    strArr.push('key=' + md5key);
                    let str = strArr.join('&');
                    let sign = crypto.createHash('md5').update(str).digest('hex').toUpperCase();
                    reqData["sign"] = sign;
                    let isDbSuc = yield ChargeDao_1.ChargeDao.insertOrder(order_id, userid, goodConfig.id, goodConfig.rmb, DateUtil_1.default.formatDateStr(DateUtil_1.default.now()), goodConfig.goodAddType, goodConfig.chargenum);
                    if (isDbSuc) {
                        let payinfo = JSON.stringify(reqData);
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Suc, "", payinfo)));
                    }
                    else {
                        resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "插入订单失败" + userid)));
                    }
                }
                else {
                    resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "不存在用户" + userid)));
                }
            }
            else {
                resp.end(JSON.stringify(ResponseModel_1.ResponseModel.create(ErrorCode_1.ErrorCode.Code.Fail, "不存在商品" + goodid)));
            }
        });
    }
    productOrder(userid) {
        let orderId = DateUtil_1.default.formatDateStr4(DateUtil_1.default.now()) + "_" + userid + "_" + this.orderOnlyId;
        this.orderOnlyId++;
        if (this.orderOnlyId >= 999) {
            this.orderOnlyId = 1;
        }
        return orderId;
    }
    third_alipay_notify_post(req, resp, ip) {
        return __awaiter(this, void 0, void 0, function* () {
            Logger_1.Logger.log("third_alipay_notify_post===ip", ip);
            // Logger.log("third_alipay_notify_post==req=", req.body)
            try {
                if (req.body) {
                    Logger_1.Logger.log("third_alipay_notify_post==req=", JSON.stringify(req.body));
                    let jsonData = JSON.parse(req.body.data);
                    Logger_1.Logger.log("third_alipay_notify_post==jsonData=", jsonData);
                    let isSuccess1 = jsonData["head"]["respCode"] == "000000" || jsonData["head"]["respMsg"] == "成功";
                    let isSuccess2 = jsonData["body"]["orderStatus"] == "1";
                    let isSuccess = true == isSuccess1 && true == isSuccess2;
                    if (true != isSuccess) {
                        Logger_1.Logger.log("订单处理失败", req.body.data);
                        Logger_1.Logger.warn("订单处理失败", req.body.data);
                        return;
                    }
                    let verify = crypto.createVerify('RSA-SHA1');
                    verify.update(req.body.data);
                    verify.end();
                    let verifyResult = verify.verify(sandPubkey, Buffer.from(req.body.sign, 'base64'));
                    if (true != verifyResult) {
                        Logger_1.Logger.log("签名验证失败");
                        Logger_1.Logger.warn("签名验证失败");
                        return;
                    }
                    let order_id = jsonData["body"]["orderCode"];
                    let orderObj = yield ChargeDao_1.ChargeDao.getOrder(order_id);
                    if (orderObj) {
                        let isDbSuc = yield ChargeDao_1.ChargeDao.finishOrder(order_id);
                        if (isDbSuc) {
                            resp.send('OK');
                            let userid = orderObj["userid"];
                            let goodid = orderObj["goodid"];
                            let goodConfig = GoodConfig_1.GoodConfig.configMap.get(goodid);
                            if (goodConfig.good_type == GoodConfig_1.GoodConfig.GoodType.BeVip) {
                                // await UserDao.set_lv(userid, 1)
                            }
                            else if (goodConfig.good_type == GoodConfig_1.GoodConfig.GoodType.ChangeVip) {
                                // await UserDao.setInvite(userid, null)
                            }
                            if (goodConfig.goodAddType == GoodConfig_1.GoodConfig.GoodAddType.gems) {
                                let addGems = goodConfig.chargenum;
                                if (addGems > 0) {
                                    // await UserDao.addGems(userid, addGems);
                                    // LogServerHelper.log_add_user_gems_history(userid, addGems, GameConfig.Gems_History_Reason.Charge, "充值了商品" + goodConfig.id + ",获得了" + addGems + "钻石")
                                }
                            }
                            if (goodConfig.good_type == GoodConfig_1.GoodConfig.GoodType.Gem || goodConfig.good_type == GoodConfig_1.GoodConfig.GoodType.Coins) {
                                // let invite: number = await UserDao.getInvite(userid)
                                // if (invite && invite > 0) {
                                //     this.sendDailiGems(invite, 1, goodConfig.rmb)
                                // }
                            }
                        }
                        else {
                            Logger_1.Logger.log("更新订单失败==", order_id);
                            Logger_1.Logger.warn("更新订单失败", order_id);
                        }
                    }
                    else {
                        Logger_1.Logger.log("订单不存在", order_id);
                        Logger_1.Logger.warn("订单不存在", order_id);
                    }
                }
            }
            catch (error) {
                // Logger.info("third_alipay_notify_post=== error=", error)
                Logger_1.Logger.error("third_alipay_notify_post=== error=", ip, error);
            }
            resp.end("to jhao server suc");
        });
    }
    sendDailiGems(userid, dailiLevel = 1, rmb) {
        return __awaiter(this, void 0, void 0, function* () {
            // let percentArr: Array<number> = [60, 10, 5, 5]
            if (dailiLevel < 3) { //最多有三级代理
                let choushui = yield SystemSettingDao_1.SystemSettingDao.get_choushui();
                let percentArr = choushui.split(",");
                let sendPercent = parseInt(percentArr[dailiLevel - 1]);
                let userData = yield UserDao_1.UserDao.get_user_data_by_userid(userid);
                let income = userData["income"];
                let qudaodaili = userData["qudaodaili"];
                if (qudaodaili == 1) {
                    sendPercent += parseInt(percentArr[3]);
                }
                sendPercent = sendPercent / 100;
                let nowIncome = income + rmb * sendPercent * 10000;
                // await UserDao.update_income(userid, nowIncome)
                let invite = userData["invite"];
                if (invite && invite > 0) {
                    dailiLevel++;
                    this.sendDailiGems(invite, dailiLevel, rmb);
                }
            }
        });
    }
}
exports.PayReqHandler = PayReqHandler;
PayReqHandler.instance = new PayReqHandler();
